package middleware

import (
	"log"
	"oa-system/pkg/errors"
	"oa-system/pkg/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			errors.HandleAPIError(c, errors.NewUnauthorizedError("需要授权头信息", nil))
			c.Abort()
			return
		}

		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			errors.HandleAPIError(c, errors.NewUnauthorizedError("授权头格式必须为Bearer {token}", nil))
			c.Abort()
			return
		}

		tokenString := parts[1]
		log.Printf("Parsing token: %s", tokenString)

		claims, err := utils.ParseToken(tokenString)
		if err != nil {
			log.Printf("Token parsing error: %v", err)
			errors.HandleAPIError(c, err)
			c.Abort()
			return
		}

		log.Printf("Token Claims: %+v", claims)
		// 将用户信息保存到上下文中
		c.Set("userID", claims.UserID)
		c.Set("email", claims.Email)

		c.Next()
	}
}
